﻿using Colorful.Furniture.ErpOrderManagement;
using Colorful.Furniture.PermissionManagement;
using Colorful.Furniture.Wrappers;
using FreeSql;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Colorful.Furniture.Extensions;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Auditing;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Users;

namespace Colorful.Furniture.ErpCustomerManagement;

/// <summary>
/// 黑名单记录服务
/// </summary>
[Authorize]
public class BlackListAppService : ApplicationService
{
    private readonly IBaseRepository<Customer> _customerRepository;
    private readonly IBaseRepository<CustomerLog> _customerLogRepository;
    private readonly IFreeSql _freeSql;
    private readonly CurrentUser _currentUser;
    private readonly ManagerAppService _managerAppService;
    private readonly IBaseRepository<SysManager> _sysManagerRepository;
    private readonly IObjectMapper _objectMapper;

    public BlackListAppService(
        IBaseRepository<Customer> customerRepository,
        IBaseRepository<CustomerLog> customerLogRepository,
        IFreeSql freeSql,
        CurrentUser currentUser,
        ManagerAppService managerAppService,
        IBaseRepository<SysManager> sysManagerRepository,
        IObjectMapper objectMapper
    )
    {
        _customerRepository = customerRepository;
        _customerLogRepository = customerLogRepository;
        _freeSql = freeSql;
        _currentUser = currentUser;
        _managerAppService = managerAppService;
        _sysManagerRepository = sysManagerRepository;
        _objectMapper = objectMapper;
    }

    
    /// <summary>
    ///  分页
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisableAuditing]
    public async Task<PageResponseWrapper<List<BlackListPageOutputDto>>> PostPagedAsync([FromBody] BlackListPagedInputDto input)
    {
        var list = await _freeSql.Select<BlackList, SysManager>()
            .LeftJoin((x, y)=>x.AddUserId == y.Id)
            .WhereIf(!string.IsNullOrWhiteSpace(input.RechargeAccount), (x,y) => x.RechargeAccount.Contains(input.RechargeAccount))
            .WhereIf(!string.IsNullOrWhiteSpace(input.Remark), (x, y) => x.Remark.Contains(input.Remark))
            .Page(input.PageIndex, input.PageSize)
            .OrderByDescending((x, y) => x.AddTime) //按照创建时间倒序
            .Count(out var pageTotalCount)
            .ToListAsync((x, y) => new BlackListPageOutputDto()
            {
                UserName = y.Name
            });
        
        var page = new PageResponseWrapper<List<BlackListPageOutputDto>>
        {
            Total = pageTotalCount,
            Items = list
        };

        return page;
    }

    /// <summary>
    ///  获取详情
    /// </summary>
    /// <returns></returns>
    [DisableAuditing]
    public async Task<BlackListBaseOutputDto> GetDetailAsync(Guid id)
    {
        var model = await _freeSql.Select<BlackList>()
            .Where(x => x.Id == id)
            .ToOneAsync(x => new BlackListBaseOutputDto());

        return model;
    }

    /// <summary>
    ///  保存黑名单信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<Guid?> SaveAsync([FromBody] BlackListSaveInputDto input)
    {
        //修改
        if (!input.Id.IsNull())
        {
            var info = _freeSql.Select<BlackList>()
                .Where(x => x.Id == input.Id).ToOne();
            if (info == null)
                throw new UserFriendlyException("黑名单信息不存在，请联系管理员！");
            
            var blackLists = _objectMapper.Map(input, info);

            await _freeSql.Update<BlackList>()
                .SetSource(blackLists)
                .ExecuteAffrowsAsync();
            
            return input.Id;
        }

        //新增
        var insert = _objectMapper.Map<BlackListSaveInputDto, BlackList>(input);
        insert.AddTime = DateTime.Now;
        insert.AddUserId = _currentUser.Id;
        await _freeSql
        .Insert(insert)
            .ExecuteAffrowsAsync();
        
        return insert.Id;
    }

    /// <summary>
    ///  批量逻辑删除
    /// </summary>
    /// <param name="idList">ID集合</param>
    /// <returns></returns> 
    public async Task<bool> DeleteBatchByIdAsync([FromBody] List<Guid?> idList)
    {
        await _freeSql.Update<BlackList>()
            .Set(x => x.IsDeleted, true)
            .Set(x => x.DeletedTime, DateTime.Now)
            .Where(x => idList.Contains(x.Id))
            .ExecuteAffrowsAsync();

        return true;
    }

}

